package services

import (
	"crypto/md5"
	"errors"
	"fmt"
	"strings"
	"time"

	"cashew.com/cashew_common/configs"
	"github.com/google/uuid"
)

func GetUploadPath(key string, fileType string) (string, string, error) {

	basePath := configs.UploadBasePath

	if basePath == "" {
		return "", "", errors.New("configs upload.base_path not found")
	}

	path, ok := configs.UploadFileKeyPathMap[strings.ToLower(key)]

	if !ok || path == "" {
		return "", "", errors.New("fileKeyPath." + key + " not found")
	}

	typePath, ok := configs.UploadFileTypePathMap[strings.ToLower(fileType)]

	if !ok || typePath == "" {
		return "", "", errors.New("fileTypePath::" + fileType + " not found")
	}

	now := time.Now()
	year := now.Format("06")
	month := now.Format("01")
	day := now.Format("02")

	path = fmt.Sprintf("%s/%s/%s/%s/%s", typePath, strings.Trim(path, "/"), year, month, day)

	return strings.TrimRight(basePath, "/"), path, nil
}

func GenerateUploadFileName(key, fileNameExt string) string {

	// 生成 UUID 并结合 key 生成 MD5
	uuidString := uuid.New().String()
	data := []byte(key + uuidString)
	hash := md5.Sum(data)

	// 将 MD5 转为字符串，并拼接文件后缀
	newFileName := fmt.Sprintf("%x.%s", hash, fileNameExt)
	return newFileName
}

func GetUploadUrl(fileName string) (string, error) {
	host := configs.FileHost

	if host == "" {
		return "", errors.New("upload::host not found")
	}

	return fmt.Sprintf("%s%s", host, fileName), nil
}
